package com.si.anddos;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.si.anddos.dpadapters.AnddosDbAdapter;
import com.si.anddos.filechooser.FileFolderChooser;

public class UploadNewActivity extends OptionsMenuActivity implements DialogInterface.OnClickListener {
	private static final int ACTIVITY_ACCOUNT_CREATE=0;

	private FileFolderChooser mFileDialog;
	
	private boolean wasNewAccountCreated = false;
	
	private Button buttonUploadCreate;
	private Button buttonNewAccount;
	private EditText editTextFile;
	private Spinner spinnerAccounts;
	private AnddosDbAdapter mDbHelper;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.upload_new);
		setTitle(R.string.titleNewUpload);
		
		editTextFile = (EditText) findViewById(R.id.editTextFile);
		spinnerAccounts = (Spinner) findViewById(R.id.spinnerAccounts);
		
		
		// on click listener for button download (not implemented yet)
		buttonUploadCreate = (Button) findViewById(R.id.buttonUploadCreate);
		buttonUploadCreate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// check for empty fields
				if (TextUtils.isEmpty(editTextFile.getText())) {
					createAlertEmptyFile();
				} else if(spinnerAccounts.getSelectedItemId() == AdapterView.INVALID_ROW_ID){
            		createAlertNoAccount();
				} else {
					saveUpload();
					setResult(RESULT_OK);
					finish();
				}
			}
		});

		// on click listener for button new account
		buttonNewAccount = (Button) findViewById(R.id.buttonNewAccount);
		buttonNewAccount.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// start new account activity for result
				Intent i = new Intent(v.getContext(), AccountNewActivity.class);
				startActivityForResult(i, ACTIVITY_ACCOUNT_CREATE);
			}
		});

		


		// create accounts db adapter
		mDbHelper = new AnddosDbAdapter(this);
		
	}

	public void chooseFile(View v) {
		mFileDialog = new FileFolderChooser(this, Environment.getExternalStorageDirectory().getAbsolutePath(), this, android.R.style.Theme_Light, true);
		mFileDialog.show();
	}
	
	private void populateAccounts() {
		mDbHelper.open();
		
		// Get all of the rows from the database and create the item list
		Cursor accountsCursor = mDbHelper.getAllAccounts();
		startManagingCursor(accountsCursor);

		// Create an array to specify the fields we want to display in the list
		// (only TITLE)
		String[] from = new String[] { AnddosDbAdapter.colAccountUsername,
				AnddosDbAdapter.colAccountService };

		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to = new int[] { R.id.textAccountRow, R.id.textAccountRowService };

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter accounts = new SimpleCursorAdapter(this,
				R.layout.account_list_row, accountsCursor, from, to);

		// disable spinner if no accounts is in database
		if (accounts.getCount() == 0)
			spinnerAccounts.setEnabled(false);
		spinnerAccounts.setAdapter(accounts);

		if (wasNewAccountCreated) {
			spinnerAccounts.setSelection(spinnerAccounts.getCount() - 1);
			wasNewAccountCreated = false;
		}
		
		mDbHelper.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
		// populate accounts from db to spinner
		populateAccounts();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if(requestCode == ACTIVITY_ACCOUNT_CREATE){
			if (resultCode != RESULT_CANCELED)
				wasNewAccountCreated = true;
		}

		super.onActivityResult(requestCode, resultCode, intent);
	}

	private void saveUpload() {
		mDbHelper.open();
		long accountId = spinnerAccounts.getSelectedItemId();
		String filePath = editTextFile.getText().toString();
		String[] items = filePath.split("/");
		String fileName = items[items.length-1];
		// save upload to database
		long id = mDbHelper.createUpload(filePath, fileName, accountId);
        if (id > 0) {
            // vse ok
        } else {
        	Toast.makeText(this, "hups", Toast.LENGTH_SHORT);
        }
        mDbHelper.close();
        
        if (!UploadProviderService.running) {
        	Intent service = new Intent(this, UploadProviderService.class);
        	this.startService(service);
        }
	}

	private void createAlertEmptyFile() {
		// create alert dialog if user left empty fields (username or password)
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(R.string.alertSaveNewUploadTitle).setMessage(
				R.string.alertSaveNewUploadMessage).setCancelable(false)
				.setNegativeButton(R.string.alertSaveNegButton,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	 private void createAlertNoAccount() {
	    	// create alert dialog if user left empty account field
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    	builder.setTitle(R.string.alertSaveNewDownloadTitle)
	    			.setMessage(R.string.alertSaveNewDownloadMessage2)
	    			.setCancelable(false)
	    			.setNegativeButton(R.string.alertSaveNegButton, new DialogInterface.OnClickListener() {
	    				public void onClick(DialogInterface dialog, int id) {
	    					dialog.cancel();
	    				}
	    			});
	    	AlertDialog alert = builder.create();
	    	alert.show();
			
		}

	public void onClick(DialogInterface dialog, int which) {
		if (dialog == mFileDialog) {
			String path = mFileDialog.getPath();
			if (path == null) {
				path = "";
			}
			editTextFile.setText(path);
		}
	}

}
